package com.example.rdemo.controller;

import com.example.rdemo.utils.PassToken;
import com.example.rdemo.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@CrossOrigin
@RestController
//@PropertySource("classpath:file/file.properties")
public class CommonController {
    @Value("${uploadfile}")
    String uploadPath;
    @PostMapping("/upload")
    public ResponseResult<String> upload(MultipartFile file) throws IOException {  //String是指图片的访问路径（虚拟路径）
        if (file.getSize()>0){
            LocalDate currentDate = LocalDate.now();
            //定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            //格式化日期为字符串
            String formatDate = currentDate.format(formatter);
            //指定路径  d:\\upload  ,不改名
//        File path = new File("d:\\upload");
            File path = new File(uploadPath,formatDate);  //资源文件读取
            if(!path.exists()){
                path.mkdirs();
            }
//        File f = new File(path,file.getOriginalFilename());  //f就是我们上传的文件
            //取后缀  newFileName新文件名称
            String newFileName = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File f = new File(path,newFileName);  //改名字
            file.transferTo(f);
            return ResponseResult.createBySuccess(200,"/upload/"+formatDate+"/"+newFileName,"上传成功");
        }else {
            return ResponseResult.createBySuccess(500,"","上传失败");
        }

    }
}
